import os
import sys
from calendar import monthrange
from datetime import datetime

import requests

# 添加项目根目录到Python路径
sys.path.append(os.path.join(os.path.dirname(__file__), '..', '..'))
from config import DB


def get_token_result():
    """获取access_token的公共方法"""
    url = "https://scrm.zuixiyu.com/flask/api/getRefreshToken"
    headers = {
        "clientId": "jackyun_web_browser_2024",
        "Content-Type": "application/json",
    }
    data = {}

    try:
        response = requests.post(url, headers=headers, json=data)
        response.raise_for_status()  # 检查请求是否成功
        result = response.json()
        print("获取Token结果:", result)

        # 检查响应结果是否为空
        if not result:
            print("获取token失败: 响应结果为空")
            return None

        # 提取access_token
        token = result.get("access_token")
        if not token:
            print("获取token失败: access_token为空")
            return None

        # 只有当token是字符串时才检查error
        if isinstance(token, str) and "error" in token:
            print("获取token失败:", token)
            return None

        return token

    except requests.exceptions.RequestException as e:
        print("请求失败:", e)
        return None
    except ValueError as e:
        print("解析JSON失败:", e)
        return None


def get_last_month_range():
    """获取上个月的起止日期"""
    today = datetime.now()
    # 获取上个月的年份和月份
    if today.month == 1:
        year = today.year - 1
        month = 12
    else:
        year = today.year
        month = today.month - 1
    # 获取上个月的最后一天
    _, last_day = monthrange(year, month)
    # 格式化日期
    start_date = f"{year}-{month:02d}-01"
    end_date = f"{year}-{month:02d}-{last_day:02d}"
    return start_date, end_date



def _get_vendor_ids_from_db(settlement_types=None):
    """支持获取所有类型的供应商查询
    Args:
        settlement_types (str|list): 可以是字符串或列表，如"月结,OEM月结"或["月结","OEM月结"]
    """
    conn = None
    cursor = None
    try:
        conn = DB()
        cursor = conn.cursor()
        
        if settlement_types:
            if isinstance(settlement_types, str):
                settlement_types = [s.strip() for s in settlement_types.split(',')]
            placeholders = ','.join(['%s'] * len(settlement_types))
            sql = f"SELECT vendor_id FROM DZ_vendor_info WHERE settlement_type IN ({placeholders})"
            cursor.execute(sql, settlement_types)
        else:
            sql = "SELECT vendor_id FROM DZ_vendor_info"
            cursor.execute(sql)
            
        vendor_ids = [str(row[0]) for row in cursor.fetchall()]
        if not vendor_ids:
            print(f"数据库中未获取到{'指定类型' if settlement_types else ''}供应商ID")
            return None
            
        print(f"从数据库获取供应商ID列表: {len(vendor_ids)} 个")
        return  ','.join(vendor_ids)  # 将列表转换为逗号分隔的字符串
    except Exception as e:
        print(f"从数据库获取供应商ID时出错: {str(e)}")
        return None
    finally:
        if cursor:
            cursor.close()
        if conn:
            conn.close()


# 从dz_real_sales_detail表中获取每个供应商名称、ID及其对应的SKU ID列表
def _get_sku_ids_from_db():
    conn = None
    cursor = None
    try:
        conn = DB()
        cursor = conn.cursor()

        sql = "SELECT sku_id FROM DZ_real_sales_detail"
        cursor.execute(sql)
        sku_ids = [str(row[0]) for row in cursor.fetchall()]
        if not sku_ids:
            print("数据库中未获取到sku_id")
            return None

        print(f"从数据库获取sku_id列表: {len(sku_ids)} 个")
        return ','.join(sku_ids)  # 修改此处，将列表转换为逗号分隔的字符串
    except Exception as e:
        print(f"从数据库获取sku_id时出错: {str(e)}")
        return None
    finally:
        if cursor:
            cursor.close()
        if conn:
            conn.close()



# 测试_get_vendor_ids_from_db函数
def _fetch_paginated_vendor_data():
    vendor_ids = _get_vendor_ids_from_db("月结,OEM月结")
    vendor_ids_str = _get_vendor_ids_from_db("实销实结,OEM实销实结")
    if vendor_ids is None:
        print("获取供应商ID列表失败，无法获取供应商数据")
        return
    print(vendor_ids)
    print("===========================", vendor_ids_str)

# 测试_get_sku_idsAndvend_id_from_db函数
def _fetch_paginated_sku_data():
    sku_data = _get_sku_ids_from_db() # 修改变量名以反映数据内容
    if sku_data is None:
        print("获取供应商SKU数据失败") # 修改提示信息
        return

